package com.margo.project.beanmapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.jdbc.core.BeanPropertyRowMapper;

import com.margo.project.append.model.BaseVO;

public class BeanPropertyMapper implements IReceiveVO {
	
	private BeanPropertyMapper(Class<?> entityClass) {
		rowMapper = null;
		this.entityClass = null;
		this.entityClass = entityClass;
		rowMapper = new BeanPropertyRowMapper<>();
	}

	public BaseVO receiveVO(ResultSet rs) throws SQLException {
		Object entity = rowMapper.mapRow(rs, 1);
		return (BaseVO) entityClass.cast(entity);
	}

	public static IReceiveVO getInstance(Class<?> entityClass) {
		return getBeanPropertyMapper(entityClass);
	}

	private static BeanPropertyMapper getBeanPropertyMapper(Class<?> entityClass) {
		BeanPropertyMapper beanMapper = (BeanPropertyMapper) mapperCache.get(entityClass);
		if (beanMapper == null) {
			beanMapper = new BeanPropertyMapper(entityClass);
			mapperCache.put(entityClass, beanMapper);
		}
		return beanMapper;
	}


	private static Map<Class<?>,BeanPropertyMapper> mapperCache = new ConcurrentHashMap<>();
	private BeanPropertyRowMapper<Object> rowMapper;
	private Class<?> entityClass;
}
